package com.wj.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

@Controller
public class HelloController {

    @Value("${sso.server.host}")
    private String host;

    @ResponseBody
    @RequestMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/employees")
    public String employees(Model model, HttpSession session, @RequestParam(required = false, value = "token") String token) {
        if (!StringUtils.isEmpty(token)) {
            RestTemplate restTemplate = new RestTemplate();
            String user = restTemplate.getForObject("http://ssoserver.com:8083/userInfo?token=" + token, String.class);
            session.setAttribute("loginUser", user);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            return "redirect:" + host + "?redirect_url=http://client1.com:8081/employees";
        } else {
            ArrayList<String> emps = new ArrayList<>();
            emps.add("qq");
            emps.add("w2w");
            model.addAttribute("emps", emps);
            return "list";
        }
    }
}
